package command

import (
	"fmt"
	"os"
	"pan/api"
	"pan/common/conf"
	"pan/common/log"

	"github.com/jedib0t/go-pretty/v6/table"
)

type DocsCommand struct {
	docType int
	simple  bool
}

func NewDocsCommand() *DocsCommand {
	return &DocsCommand{}
}

func (d *DocsCommand) Run(opts []*Option, args []string) {
	if !d.parseOption(opts) {
		return
	}
	if !conf.IsTokenValid() {
		panic("token is invalid, you must login first")
	}

	req := &api.DocsRequest{
		DocType: d.docType,
	}
	rsp, err := api.DocsApi(conf.GlobalToken.Tokenid, req)
	if err != nil {
		panic(err)
	}
	if d.simple {
		d.printSimple(rsp.DocInfos)
	} else {
		d.printDocs(rsp.DocInfos)
	}
}

func (d *DocsCommand) parseOption(opts []*Option) bool {
	for _, opt := range opts {
		switch opt.Name {
		case "type":
			d.docType = opt.IntValue
		case "simple":
			d.simple = opt.BoolValue
		}
	}
	if d.docType < 0 || d.docType > 6 {
		log.Error("docs type is invalid")
		return false
	}
	return true
}

func (d *DocsCommand) Arguments() []Argument {
	return nil
}

func (d *DocsCommand) Options() []*Option {
	return []*Option{
		{
			ShortName:    "t",
			Name:         "type",
			Description:  "docs type. 0-all, 1-user, 2-user group, 3-custom, 4-share user, 5-archive, 6-share user group",
			OptType:      IntOption,
			DefaultValue: 0,
		},
		{
			ShortName:    "s",
			Name:         "simple",
			Description:  "show simple content",
			OptType:      BoolOption,
			DefaultValue: false,
		},
	}
}

func (d *DocsCommand) Description() string {
	return "Show doc list"
}

func (d *DocsCommand) printDocs(docs []api.DocInfo) {
	if docs == nil || len(docs) == 0 {
		return
	}
	tbl := table.NewWriter()
	tbl.SetOutputMirror(os.Stdout)
	tbl.AppendHeader(table.Row{"#", "doctype", "typename", "docid", "name"})

	for i, doc := range docs {
		tbl.AppendRow(table.Row{i + 1, doc.DocType, doc.TypeName, doc.Docid, doc.Name})
		tbl.AppendSeparator()
	}
	tbl.Render()
}

func (d *DocsCommand) printSimple(docs []api.DocInfo) {
	if docs == nil || len(docs) == 0 {
		return
	}
	for _, doc := range docs {
		fmt.Printf("%d, %s, %s, %s\n", doc.DocType, doc.TypeName, doc.Docid, doc.Name)
	}
}
